#!/bin/bash

DIR=`pwd`
PRO=SetupTool-V$1
BootPRO=klbootmgr-V$1
PRODIR=$DIR/$PRO
BootPRODIR=$DIR/$BootPRO
TOOLDIR="$(dirname "$0")"
FLASHROMDIR=$TOOLDIR/../FlashRom
UEFIDIR=$TOOLDIR/../uefitool-new_engine/UEFIExtract
IFRDIR=$TOOLDIR/../universal-ifr-extractor-master
CONMODDIR=$TOOLDIR/../universal-ifr-extractor-master/config_modify
BIOSVENDOR="KunlunTech"
COPYRIGHT="Kunlun BIOS, Kunlun Technology (Beijing) Co., Ltd."
PACKDIR=$TOOLDIR/pack

if (( $# <= 0 )) ; then
  echo "Please add version, for example : 1.4.1 [clean]"
  echo "Copyright (c) 2005-2022, Kunlun BIOS, Kunlun Technology (Beijing) Co., Ltd."
  exit 1;
fi

if [[ $2 =~ "clean" ]] ; then
  echo clean $PRO
  echo rm $PRODIR $PRO.zip
  rm -rf $PRODIR $PRO.zip

  echo clean $BootPRO
  echo rm $BootPRODIR $BootPRO.zip
  rm -rf $BootPRODIR $BootPRO.zip
  exit 0
elif [ -n "$2" ]; then
  BIOSVENDOR="$2"
fi

if [ -n "$3" ]; then
  COPYRIGHT="$3"
fi

mkdir $PRODIR

cd $FLASHROMDIR 
chmod 777 ./util/getrevision.sh
make CONFIG_STATIC=yes CONFIG_FT2232_SPI=no CONFIG_USBBLASTER_SPI=no  CONFIG_ENABLE_LIBUSB1_PROGRAMMERS=no 
cd $DIR

cd $UEFIDIR

cmake .
make 
cd $DIR

cd $IFRDIR
cmake .
make 
cd $DIR

cd $CONMODDIR
gcc -static main.c cJSON.c -lm -o config_modify_tool
echo "gcc -static main.c cJSON.c -lm -o config_modify_tool"
cd $DIR

cd $PACKDIR
make clean
make BIOS_VENDOR="$BIOSVENDOR" COPY_RIGHT="$COPYRIGHT"

cd $PRODIR
FLASHROM=(../$FLASHROMDIR/flashrom ../$FLASHROMDIR/libpci.so.3)
TOOLFILE=(../$IFRDIR/klsetuptool.sh ../$IFRDIR/setuptool.sh ../$IFRDIR/setuptool_layout.sh ../$IFRDIR/ifrextract  ../$IFRDIR/config_modify/config_modify_tool   ../$UEFIDIR/UEFIExtract)
../$PACKDIR/Pack SetupTool 9 ../$PACKDIR/Setup ${TOOLFILE[*]} ${FLASHROM[*]}

cp -r ../$TOOLDIR/SetupTool_ReleaseNote.txt $PRODIR
cp -r ../$TOOLDIR/SetupTool_readme.txt $PRODIR

chmod -R 777 ../$TOOLDIR/$(uname -m)/SetupUi/
cp -r ../$TOOLDIR/$(uname -m)/SetupUi/* $PRODIR

cp SetupTool $DIR/Kunlun/usr/libexec/com.kunluntech.SetupTool/
cp UiComp $DIR/Kunlun/usr/libexec/com.kunluntech.SetupTool/
strip --strip-unneeded  $DIR/Kunlun/usr/libexec/com.kunluntech.SetupTool/SetupTool
cd $DIR

zip -rq $PRO.zip $PRO/*
